<template>
  <div class="ai-chat-bg">
    <div class="ai-chat-container">
      <div class="ai-chat-sidebar">
        <div class="ai-chat-sidebar-header">
          <span>对话记录</span>
          <button class="ai-chat-new-btn" @click="createNewChat">开启新对话</button>
        </div>
        <div class="ai-chat-history">
          <div v-for="(item, idx) in chatHistory" :key="idx" class="ai-chat-history-item" :class="{active: idx === selectedHistory}" @click="selectHistory(idx)">
            <div class="ai-chat-history-title">{{ item.title }}</div>
          </div>
        </div>
      </div>
      <div class="ai-chat-main">
        <div class="ai-chat-header">
          <img src="../assets/image.png" alt="AI Logo" class="ai-chat-logo" />
          <span class="ai-chat-title">AI助手</span>
        </div>
        <div class="ai-chat-desc">我可以帮你推荐你想看的小说，请把你的任务交给我吧~</div>
        <div class="ai-chat-messages" ref="messagesContainer">
          <div v-for="(msg, idx) in messages" :key="idx" :class="['ai-chat-message', msg.role]">
            <div class="ai-chat-bubble" v-if="msg.role === 'user'">{{ msg.content }}</div>
            <div class="ai-chat-bubble ai-markdown" v-else v-html="renderMarkdown(msg.content)"></div>
          </div>
        </div>
        <div class="ai-chat-input-bar">
          <input v-model="input" @keyup.enter="sendMessage" placeholder="给 AI 发送消息" class="ai-chat-input" />
          <button @click="sendMessage" class="ai-chat-send-btn">发送</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {getChatMemoryList,getMemoryByChatId} from '@/api/ai.js'
import { getToken } from '@/utils/auth'
import { marked } from 'marked'

// // 1. AI对话接口
// export function aiChatAsk(chatId, message) {
//   return request({
//     url: '/api/front/help/ai/aihelp/ask',
//     method: 'get',
//     params: { chatId, message }
//   })
// }

// // 2. 查询用户聊天记录
// export function getChatMemoryList() {
//   return request({
//     url: '/api/front/book/aihelp/getMemoryList',
//     method: 'get'
//   })
// }

// // 3. 根据chatId查询聊天内容
// export function getMemoryByChatId(chatId) {
//   return request({
//     url: '/ai/getMemoryByChatId',
//     method: 'get',
//     params: { chatId }
//   })
// }

export default {
 
  name: 'AiChat',
  data() {
    return {
      chatHistory: [],
      selectedHistory: 0,
      messages: [],
      input: '',
      currentChatId: '',
      isStreaming: false,
    }

  },
  created() {
    this.loadChatHistory()
    // 配置marked选项
    marked.setOptions({
      breaks: true, // 支持换行
      gfm: true, // 支持GitHub风格的Markdown
      sanitize: false // 允许HTML标签
    })
  },
  methods: {
    // 生成唯一的chatId
    generateChatId() {
      return 'chat_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
    },
    // 创建新对话
    createNewChat() {
      const newChatId = this.generateChatId()
      const newChat = {
        chatId: newChatId,
        title: '新对话',
        createTime: new Date().toISOString()
      }
      
      // 添加到聊天历史
      this.chatHistory.unshift(newChat)
      this.selectedHistory = 0
      this.currentChatId = newChatId
      this.messages = []
      
      // 滚动到顶部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },
    // 滚动到底部
    scrollToBottom() {
      if (this.$refs.messagesContainer) {
        this.$refs.messagesContainer.scrollTop = this.$refs.messagesContainer.scrollHeight
      }
    },
    // 渲染Markdown内容
    renderMarkdown(content) {
      if (!content) return ''
      try {
        return marked.parse(content)
      } catch (error) {
        console.error('Markdown渲染错误:', error)
        return content
      }
    },
    // 1. 查询用户聊天记录
    async loadChatHistory() {
      const res = await getChatMemoryList()
      if (res && res.data) {
        this.chatHistory = res.data
        if (this.chatHistory.length > 0) {
          this.selectHistory(0)
        }
      }
    },
    // 2. 选择某个聊天记录并查询内容
    async selectHistory(idx) {
      this.selectedHistory = idx
      const chat = this.chatHistory[idx]
      this.currentChatId = chat.chatId
      const res = await getMemoryByChatId(chat.chatId)
      if (res && res.data) {
        this.messages = res.data.map(item => ({
          role: item.type === 'user' ? 'user' : 'ai',
          content: item.content
        }))
        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
    },
    // 3. 发送消息
    async sendMessage() {
      if (!this.input.trim() || this.isStreaming) return;
      
      // 如果没有当前聊天，创建新聊天
      if (!this.currentChatId) {
        this.createNewChat()
      }
      
      this.messages.push({ role: 'user', content: this.input });
      const userMsg = this.input;
      this.input = '';

      const chatId = this.currentChatId;
      const params = new URLSearchParams({ chatId, message: userMsg }).toString();
      const token = getToken();

      this.isStreaming = true;
      this.messages.push({ role: 'ai', content: '' }); // 先插入一条空的AI消息
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })

      try {
        const response = await fetch(`${process.env.VUE_APP_BASE_API_URL}/front/help/ai/ask?${params}`, {
          method: 'GET',
          headers: {
            'Accept': 'text/event-stream',
            'Authorization': token ? `${token}` : ''
          }
        });

        if (!response.body) return;

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let buffer = '';

        while (true) { // eslint-disable-line no-constant-condition
          const { done, value } = await reader.read();
          if (done) break;
          buffer += decoder.decode(value, { stream: true });

          // 处理多行（有可能一次收到多行data:）
          let lines = buffer.split('\n');
          buffer = lines.pop(); // 剩下的留到下次

          for (let line of lines) {
            line = line.trim();
            if (line.startsWith('data:')) {
              let content = line.replace(/^data:\s*/, '');
              if (content === '[DONE]' || content === '') continue; // 结束标记或空行跳过
              // 追加到当前AI消息
              let lastIdx = this.messages.length - 1;
              this.messages[lastIdx].content += content;
              
              // 实时滚动到底部
              this.$nextTick(() => {
                this.scrollToBottom()
              })
            }
          }
        }
      } catch (error) {
        console.error('发送消息错误:', error)
        // 如果出错，移除空的AI消息
        if (this.messages.length > 0 && this.messages[this.messages.length - 1].role === 'ai' && this.messages[this.messages.length - 1].content === '') {
          this.messages.pop()
        }
      } finally {
        this.isStreaming = false
      }
    }
  }
}
</script>

<style scoped>
.ai-chat-bg {
  background: #f7f8fa;
  min-height: calc(100vh - 60px);
  padding: 32px 0 0 0;
}
.ai-chat-container {
  display: flex;
  width: 1600px;
  min-height: 800px;
  height: 80vh;
  margin: 0 auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 16px 0 rgba(255,136,0,0.08);
  overflow: hidden;
}
.ai-chat-sidebar {
  width: 240px;
  background: #fff7ec;
  border-right: 1px solid #ffe0b2;
  display: flex;
  flex-direction: column;
  /* position: relative;  // 移除relative，避免sticky失效 */
  height: 100%;
}
.ai-chat-sidebar-header {
  padding: 18px 16px 10px 16px;
  font-weight: bold;
  font-size: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #ff8800;
  background: #fff7ec;
  position: sticky;
  top: 0;
  z-index: 10;
}
.ai-chat-new-btn {
  background: #fff3e0;
  border: 1px solid #ffbb66;
  border-radius: 4px;
  padding: 4px 10px;
  color: #ff8800;
  cursor: pointer;
  font-size: 13px;
  transition: background 0.2s;
}
.ai-chat-new-btn:hover {
  background: #ffe0b2;
}
.ai-chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 0 8px 8px 8px;
  /* 让历史列表填满剩余高度 */
  height: 0;
  min-height: 0;
}
.ai-chat-history-item {
  padding: 10px 12px;
  border-radius: 6px;
  margin-bottom: 6px;
  cursor: pointer;
  background: #fff;
  transition: background 0.2s, color 0.2s;
  border: 1px solid transparent;
}
.ai-chat-history-item.active {
  background: #fff3e0;
  color: #ff8800;
  border: 1px solid #ffbb66;
}
.ai-chat-history-title {
  font-size: 14px;
}
.ai-chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  height: 100%;
  min-height: 0;
}
.ai-chat-header {
  display: flex;
  align-items: center;
  padding: 32px 0 8px 0;
  justify-content: center;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
}
.ai-chat-logo {
  width: 38px;
  height: 38px;
  margin-right: 12px;
}
.ai-chat-title {
  font-size: 22px;
  font-weight: bold;
  color: #ff8800;
  letter-spacing: 2px;
}
.ai-chat-desc {
  text-align: center;
  color: #888;
  font-size: 15px;
  margin-bottom: 18px;
  background: #fff;
  position: sticky;
  top: 70px;
  z-index: 10;
  padding: 0 32px;
}
.ai-chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 0 32px 0 32px;
  display: flex;
  flex-direction: column;
  min-height: 0;
}
.ai-chat-message {
  margin-bottom: 16px;
  display: flex;
}
.ai-chat-message.user {
  justify-content: flex-end;
}
.ai-chat-message.ai {
  justify-content: flex-start;
}
.ai-chat-bubble {
  max-width: 60%;
  padding: 10px 16px;
  border-radius: 16px;
  background: #f7f8fa;
  color: #222;
  font-size: 15px;
  word-break: break-all;
  box-shadow: 0 2px 8px 0 rgba(255,136,0,0.06);
}
.ai-chat-message.user .ai-chat-bubble {
  background: #fff3e0;
  color: #ff8800;
  border: 1px solid #ffbb66;
}
.ai-chat-input-bar {
  display: flex;
  padding: 18px 32px 18px 32px;
  border-top: 1px solid #ffe0b2;
  background: #fff;
  /* position: sticky; bottom: 0; z-index: 10;  改为flex布局下的自然底部 */
}
.ai-chat-input {
  flex: 1;
  border: 1px solid #ffe0b2;
  border-radius: 6px;
  padding: 10px 14px;
  font-size: 15px;
  outline: none;
}
.ai-chat-send-btn {
  margin-left: 12px;
  background: #ff8800;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 0 22px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}
.ai-chat-send-btn:hover {
  background: #ffbb66;
}

/* Markdown样式 */
.ai-markdown {
  line-height: 1.6;
}

.ai-markdown h1,
.ai-markdown h2,
.ai-markdown h3,
.ai-markdown h4,
.ai-markdown h5,
.ai-markdown h6 {
  margin: 16px 0 8px 0;
  font-weight: bold;
  color: #333;
}

.ai-markdown h1 { font-size: 20px; }
.ai-markdown h2 { font-size: 18px; }
.ai-markdown h3 { font-size: 16px; }
.ai-markdown h4 { font-size: 15px; }
.ai-markdown h5 { font-size: 14px; }
.ai-markdown h6 { font-size: 13px; }

.ai-markdown p {
  margin: 8px 0;
}

.ai-markdown ul,
.ai-markdown ol {
  margin: 8px 0;
  padding-left: 20px;
}

.ai-markdown li {
  margin: 4px 0;
}

.ai-markdown code {
  background: #f1f3f4;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  color: #d73a49;
}

.ai-markdown pre {
  background: #f6f8fa;
  border: 1px solid #e1e4e8;
  border-radius: 6px;
  padding: 12px;
  margin: 12px 0;
  overflow-x: auto;
}

.ai-markdown pre code {
  background: none;
  padding: 0;
  color: #333;
}

.ai-markdown blockquote {
  border-left: 4px solid #ff8800;
  margin: 12px 0;
  padding: 8px 16px;
  background: #fff7ec;
  color: #666;
}

.ai-markdown strong {
  font-weight: bold;
  color: #333;
}

.ai-markdown em {
  font-style: italic;
  color: #666;
}

.ai-markdown a {
  color: #ff8800;
  text-decoration: none;
}

.ai-markdown a:hover {
  text-decoration: underline;
}

.ai-markdown table {
  border-collapse: collapse;
  width: 100%;
  margin: 12px 0;
}

.ai-markdown th,
.ai-markdown td {
  border: 1px solid #e1e4e8;
  padding: 8px 12px;
  text-align: left;
}

.ai-markdown th {
  background: #f6f8fa;
  font-weight: bold;
}

.ai-markdown hr {
  border: none;
  border-top: 1px solid #e1e4e8;
  margin: 16px 0;
}
</style> 